import React, { useState, useEffect } from 'react'
import EditForm from './EditForm'
import {
    selectStudentAsync,
    deleteStudentAsync,
    updateStudentAsync,
    createStudentAsync
} from '../../api/student'
import { selectClassAsync } from '../../api/class'
import { addStudentScoreAsync, removeStudentScoreAsync } from '../../api/score'
import { Table, Space, Button, Popconfirm } from 'antd'
import './style.less'

function Student() {
    const [studentData, setStudentData] = useState([])
    const [classData, setClassData] = useState([])
    const [showData, setShowData] = useState([])
    const [tableLoading, setTableLoading] = useState(true)
    const [modalVisible, setModalVisible] = useState(false)
    const [isEdit, setIsEdit] = useState(false)
    const [modalData, setModalData] = useState([])
    // 异步请求函数抽象
    const asyncRequest = async (fn, payload) => {
        payload = payload || []
        const res = await fn(...payload)
        if (res.code === 0) {
            return res.data ? res.data : true
        }
    }
    useEffect(() => {
        async function asyncFn() {
            setTableLoading(true)
            setStudentData(await asyncRequest(selectStudentAsync))
            setClassData(await asyncRequest(selectClassAsync))
            setTableLoading(false)
        }
        asyncFn()
    }, [])
    useEffect(() => {
        setShowData(
            studentData.map((item, i) => {
                // console.log(item)
                item.index = i + 1
                const list = classData.filter(
                    (cell) => +cell.no === +item.classNo
                )
                // console.log(list)
                item.className = list[0] ? list[0].name : null
                // console.log(item)
                return item
            })
        )
    }, [classData, studentData])

    // 添加按钮点击事件
    const addButtonEvent = () => {
        setModalVisible(true)
        setIsEdit(false)
        setModalData({
            no: null,
            type: 'S',
            name: '',
            sex: '男'
        })
    }
    // 修改按钮点击事件
    const editButtonEvent = (text, record) => {
        setModalVisible(true)
        setIsEdit(true)
        setModalData(record)
    }
    // 删除按钮点击事件
    const deleteButtonEvent = async (text, record) => {
        setTableLoading(true)
        if (
            (await asyncRequest(deleteStudentAsync, [record.no])) &&
            (await asyncRequest(removeStudentScoreAsync, [record.no]))
        ) {
            setStudentData(await asyncRequest(selectStudentAsync))
            setTableLoading(false)
        }
    }
    // 对话框中确定事件
    const modalOk = async (data, oldData) => {
        setModalVisible(false)
        setTableLoading(true)
        data.type = 'S'
        data.classNo = classData.filter(
            (item) => item.name === data.className
        )[0].no
        delete data.className
        if (isEdit) {
            if (await asyncRequest(updateStudentAsync, [data, oldData])) {
                setStudentData(await asyncRequest(selectStudentAsync))
                setTableLoading(false)
            }
        } else {
            if (
                (await asyncRequest(createStudentAsync, [data])) &&
                (await asyncRequest(addStudentScoreAsync, [data.no]))
            ) {
                setStudentData(await asyncRequest(selectStudentAsync))
                setTableLoading(false)
            }
        }
    }
    // 对话框中取消事件
    const modalCancel = () => {
        setModalVisible(false)
    }
    // 判断学号是否重复
    const isRepeat = (no) => {
        return showData.some((item) => +item.no === +no)
    }

    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            sorter: (a, b) => a.index - b.index
        },
        {
            title: '学号',
            dataIndex: 'no',
            key: 'no',
            sorter: (a, b) => a.no - b.no
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            sorter: (a, b) => a.name.localeCompare(b.name)
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            filters: [
                {
                    text: '男',
                    value: '男'
                },
                {
                    text: '女',
                    value: '女'
                }
            ],
            onFilter: (value, record) => record.sex.indexOf(value) === 0
        },
        {
            title: '班级',
            key: 'className',
            dataIndex: 'className',
            filters: classData.map((item) => ({
                text: item.name,
                value: item.name
            })),
            onFilter: (value, record) => record.className.indexOf(value) === 0
        },
        {
            title: '操作',
            key: 'handle',
            render: (text, record) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        onClick={() => {
                            editButtonEvent(text, record)
                        }}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="是否确认删除？"
                        onConfirm={() => {
                            deleteButtonEvent(text, record)
                        }}
                        okText="删除"
                        cancelText="取消"
                    >
                        <Button type="danger">删除</Button>
                    </Popconfirm>
                </Space>
            )
        }
    ]

    return (
        <div className="student-page-container">
            <div className="button-header">
                <Button type="primary" onClick={addButtonEvent}>
                    添加学生
                </Button>
            </div>
            <Table
                columns={columns}
                dataSource={showData}
                rowKey={(item) => item.no}
                loading={tableLoading}
            />
            <EditForm
                modalVisible={modalVisible}
                modalOk={modalOk}
                modalCancel={modalCancel}
                isEdit={isEdit}
                modalData={modalData}
                classData={classData}
                isRepeat={isRepeat}
            />
        </div>
    )
}

export default Student
